package com.qfmy.web.service.impl;

import com.qfmy.web.entity.minio.MinioProperties;
import com.qfmy.web.mapper.FileUploadMapper;
import com.qfmy.web.service.FileUploadService;
import com.qfmy.web.utils.LoginUserHolder;
import io.jsonwebtoken.Claims;
import io.minio.*;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@SuppressWarnings("all")
public class FileUploadServiceImpl implements FileUploadService {
    @Resource
    private MinioClient mc;
    @Resource
    private MinioProperties mp;
    @Resource
    private FileUploadMapper fileUploadMapper;
    /**
     * 文件上传的方法
     * @param file
     * @return
     */
    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        String url = null;
        //判断桶是否存在，不存在则创建
        boolean b = mc.bucketExists(BucketExistsArgs.builder()
                .bucket(mp.getBucketName()).build());
        if (!b) {
            //创建桶
            mc.makeBucket(MakeBucketArgs.builder()
                    .bucket(mp.getBucketName()).build());
            //设置桶策略
            mc.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(mp.getBucketName())
                    .config(BuckerName(mp.getBucketName()))
                    .build());

        }
        //使用UUID生成文件名
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "/" + UUID.randomUUID() + "-"
                + file.getOriginalFilename();
        //上传文件
        mc.putObject(PutObjectArgs.builder()
                .bucket(mp.getBucketName())
                .stream(file.getInputStream(),file.getSize(),-1).object(filename)
                //设置文件类型->为了让浏览器不下载直接打开所以要设置文件类型
                .contentType(file.getContentType())
                .build());
        //拼接url
        url = String.join("/",mp.getEndpoint(),mp.getBucketName(),filename);
        //从当前线程中获取登录用户
        Claims claims = ( Claims) LoginUserHolder.get();
        //获取用户id
        Long id = claims.get("id", Long.class);
        //判断文件还是头像、
        String[] split = file.getOriginalFilename().split(".");
        if(split[1].equals("jpg")||split[1].equals("png")||split[1].equals("jpeg"))
        {
            //更新用户头像
            fileUploadMapper.updateImageById(url,id);
        }
        //返回url
        return url;
    }


    /**
     * 获取桶的名称
     * @param bucketName
     * @return
     */
    public String BuckerName(String bucketName)
    {
        return """
                  {
                    "Statement" : [ {
                      "Action" : "s3:GetObject",
                      "Effect" : "Allow",
                      "Principal" : "*",
                      "Resource" : "arn:aws:s3:::%s/*"
                    } ],
                    "Version" : "2012-10-17"
                  }
                  """.formatted(bucketName);
    }


}
